jetcrab\bytecode\statements/
if_statement.rs

1use crate::ast::Node;
2use crate::vm::instructions::Instruction;
3use crate::vm::types::CodeAddress;
4
5use super::ControlFlowCore;
6
7pub fn generate_if_statement<T>(this: &mut T, node: &Node)
8where
9    T: ControlFlowCore,
10{
11    if let Node::IfStatement(stmt) = node {
12        // Generate test condition
13        this.visit_node(&stmt.test);
14
15        // Jump to else block if condition is false
16        let jump_to_else_pos = this.instructions().len();
17        this.instructions()
18            .push(Instruction::JumpIfFalse(CodeAddress::new(0))); // Placeholder
19
20        // Generate consequent block
21        this.visit_node(&stmt.consequent);
22
23        // Jump over else block
24        let jump_over_else_pos = this.instructions().len();
25        this.instructions()
26            .push(Instruction::Jump(CodeAddress::new(0))); // Placeholder
27
28        // Update jump to else address
29        let else_start_pos = this.instructions().len();
30        this.instructions()[jump_to_else_pos] =
31            Instruction::JumpIfFalse(CodeAddress::new(else_start_pos));
32
33        // Generate alternate block (else)
34        if let Some(alt) = &stmt.alternate {
35            this.visit_node(alt);
36        }
37
38        // Update jump over else address
39        let end_pos = this.instructions().len();
40        this.instructions()[jump_over_else_pos] = Instruction::Jump(CodeAddress::new(end_pos));
41    }
42}